package com.xbq.exceleditor.ui.filechooser

import android.os.Bundle
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.xbq.exceleditor.R
import com.xbq.exceleditor.databinding.FragmentFileByContentResolverListBinding
import com.xbq.exceleditor.ui.filechooser.media.FileTypeEnum
import com.xbq.exceleditor.ui.filechooser.media.MediaStoreUtils
import com.xbq.xbqsdk.component.activity.VBFragment
import com.xbq.xbqsdk.util.click.onDebouncedClick
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * Author: liaohaiping
 * Time: 2018-07-25
 * Description:
 */
@AndroidEntryPoint
class FileByContentResolverListFragment :
    VBFragment<FragmentFileByContentResolverListBinding>() {
    private val adapter by lazy { FileAdapter() }
    private var fileType: FileTypeEnum? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        parseArguments()
        if (fileType != null) {
            binding.etKeyWord.addTextChangedListener {
                loadAllFiles(it.toString().trim())
            }
            binding.rvImagelist.let {
                it.layoutManager = LinearLayoutManager(requireContext())
                it.adapter = adapter
                adapter.setOnItemClickListener { adt, view, position ->
                    val item = adapter.getItem(position)
                    adapter.selectFile(item)
                    EventBus.getDefault().post(item)
                }
            }
            binding.ivSearch.onDebouncedClick {
                loadAllFiles(binding.etKeyWord.text.toString().trim())
            }
            loadAllFiles("")
        }
    }

    fun parseArguments() {
        val fileTypeName = arguments?.getString(EXTRA_FILE_TYPE)
        fileTypeName?.let {
            fileType = FileTypeEnum.valueOf(it)
        }
    }

    private fun loadAllFiles(fileName: String) {
        if (fileType == null) return

        lifecycleScope.launch {
            val files = MediaStoreUtils.scanFileByType(requireContext(), fileType!!, fileName)
            adapter.setList(files.map { File(it.filePath) })
            adapter.setEmptyView(R.layout.recycle_no_data)
        }
    }


    companion object {
        const val EXTRA_FILE_TYPE = "EXTRA_FILE_TYPE"

        fun newFragment(fileType: FileTypeEnum): FileByContentResolverListFragment {
            return FileByContentResolverListFragment().apply {
                val args = Bundle()
                args.putString(FileByExtensionListFragment.EXTRA_FILE_TYPE, fileType.name)
                arguments = args
            }
        }
    }
}